package com.llsydn.a01androidh5;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * @author lilinshen
 * @title Java代码和H5代码互调
 * @description js调用java，打电话
 * @date 2018/10/19 14:56
 */
public class JsJavaPhoneActivity extends AppCompatActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_java_phone);

        webView = findViewById(R.id.webViewPhone);
        WebSettings webSettings = webView.getSettings();
        //设置支持js代码
        webSettings.setJavaScriptEnabled(true);
        //不调起浏览器-自定义浏览器
        webView.setWebViewClient(new WebViewClient());

        //添加JavascriptInterface
        //以后js通过android字段，调用JavascriptInterface的任何方法。例如：window.Android.xxxx
        webView.addJavascriptInterface(new AndroidAndJsInterface(), "Android");

        //加载网页（网络或本地的）
        //webView.loadUrl("http://www.zhongshanou.cn/ddmh/portal/home/index.jhtml");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("file:///android_asset/JsCallJavaCallPhone.html");
            }
        });
    }


    /**
     * js调java
     */
    class AndroidAndJsInterface {
        @JavascriptInterface
        public void call(String phone) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
            if (ActivityCompat.checkSelfPermission(JsJavaPhoneActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(JsJavaPhoneActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 0);
                return;
            }
            startActivity(intent);
        }

        /**
         * 将会被js调用
         */
        @JavascriptInterface
        public void showcontacts() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
                    // 调用JS中的方法
                    webView.loadUrl("javascript:show('" + json + "')");
                }
            });
        }
    }
}
